<template>
  <div
    ref="dialogBody"
    v-loading="loading"
    element-loading-text="物资申领中,请稍后..."
    class="zr-pms-material"
  >
    <div class="flex-box mb-10">
      <div v-if="!!flag" class="flex-box-left">
        <span>{{ projectInfo.projectName }}</span>-<span>{{ projectInfo.orgName }}</span>【<span
          v-debounce="()=>jump(projectInfo.prjCode)"
          class="click-row"
        >{{ projectInfo.prjCode }}</span>】
        <span v-if="sjbgcheck" class="color-red">设计变更中</span>
        <span v-if="!reState" class="color-red"> 销项项目 </span>
      </div>
      <div
        v-if=" powerPermisson?newPowerShow(): (!sjbgcheck&&reState) && acceptcheck && outPut"
        class="flex-box-right"
        :class="{ 'position-abs': !flag, 'abs-right': !flag }"
      >
        <span>计划领用时间</span>
        <el-date-picker
          ref="pmsElDatePicker"
          v-model="planGetTime"
          :disabled="!isEdit || !metaEdit "
          type="date"
          placeholder="选择日期"
          :append-to-body="appendToBody"
          class="pms-el-datepicker"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          style="margin-right: 12px; margin-left: 12px"
        />
        <el-button
          v-if="powerPermisson?newPowerShow(): outPut && isEdit && metaEdit"
          v-debounce="handleAllApply"
          :disabled="loadingButton"
          class="pms-button-primary mb-5"
        >全部领用</el-button>
        <el-button
          v-if="powerPermisson?newPowerShow(): outPut && isEdit && metaEdit"
          v-debounce="handleApply"
          :disabled="loadingButton"
          class="pms-button-primary mb-5"
        >确认领用</el-button>
        <el-button
          v-if="powerPermisson?newPowerShow(): outPut && isEdit && metaEdit && checkAdjustButton"
          v-debounce="adjustProject"
          class="pms-button-primary mb-5"
        >跨项目调整</el-button>
      </div>
    </div>
    <wz-table
      :columns="wzApplicationColumn"
      :use-index="true"
      :table-data="designData"
    >
      <!-- 设计数量 -->
      <!-- 累计申领数量 -->
      <template #header="{ col }">
        <div v-if="col.details">
          <el-tooltip
            class="item"
            effect="dark"
            :content="col.details"
            placement="top-start"
          >
            <span> {{ col.label }}</span>
          </el-tooltip>
        </div>
        <div v-else>
          {{ col.label }}
        </div>
      </template>
      <template #ifSourceCode="{ row }">
        <div>
          {{ ifSourceCode(row.ifSourceCode) }}
        </div>
      </template>
      <!-- 按备电标准化成品申领 -->
      <template #isStandValue="{ row }">
        <div v-if="+row.isStand">
          <div
            v-if="
              row.isStandValue === '0' || row.isStandValue === '1'
            "
          >
            {{ +row.isStandValue ? "是" : "否" }}
          </div>
          <div v-else>
            <el-select
              v-model="row.addStandValue"
              :popper-append-to-body="true"
              size="mini"
              style="width: 100%"
              class="pms-zr-docCodeClass pms-zr-select"
              placeholder="请选择"
              @change="(value) => docTypeChange(value, row)"
            >
              <el-option
                v-for="it in isStandValueOptions"
                :key="it.value"
                :label="it.label"
                :value="it.value"
              />
            </el-select>
          </div>
        </div>
        <div v-else>
          {{ +row.isStandValue ? "是" : "否" }}
        </div>
      </template>
      <!-- 本次申领数量 -->
      <template #applyNum="{ row }">
        <div class="pms-wz-input-wrapper" >
          <el-input
            v-if="outPut"
            v-model="row.applyNum"
            :disabled="+projectInfo.isNewAcceptance===1&&+projectInfo.acceptcheck===1&&+row.jwMateReceive===1?permissionChange(row):nonarrivalDisabled(row) || !isEdit||!(!sjbgcheck && reState) || !metaEdit"
            class="pms-wz-input el-table-inline"
          />
        </div>
      </template>
      <template #osRealAmount="{ row }">
        <div v-if="+row.retreatAmount">
          <!--          <el-tooltip-->
          <!--            effect="dark"-->
          <!--            :content="`累计出库总数:${row.osAmount},累计已完成退库总数:${row.retreatAmount}`"-->
          <!--            placement="top"-->
          <!--          >-->
          <div>
            {{
              `${row.osRealAmount}(${row.osAmount}-${row.retreatAmount})`
            }}
          </div>
          <!--          </el-tooltip>-->
        </div>
        <div v-else>{{ row.osRealAmount }}</div>
      </template>
      <template #sumReceiveAmount="{ row }">
        <div v-if="+row.backAmount">
          <!--          <el-tooltip-->
          <!--            effect="dark"-->
          <!--            :content="`累计申领单总数:${row.receiveAmount},累计撤销申领总数:${row.backAmount}`"-->
          <!--            placement="top"-->
          <!--          >-->
          <div>
            {{
              `${row.sumReceiveAmount}(${row.receiveAmount}-${row.backAmount})`
            }}
          </div>
          <!--          </el-tooltip>-->
        </div>
        <div v-else>{{ row.sumReceiveAmount }}</div>
      </template>
    </wz-table>
    <div
      v-if="powerPermisson?newPowerShow(): (!sjbgcheck&&reState) && acceptcheck"
      class="mt-10 materials-remark-wrapper"
    >
      <div class="materials-remark-wrapper-title">物资申领备注</div>
      <el-input
        v-model="materialsRemarks"
        type="textarea"
        :rows="2"
        :disabled="!isEdit || !metaEdit"
        placeholder="请输入物资申领备注"
      />
    </div>
    <adjust-project-dialog v-if="showAdjustProject" :visible.sync="showAdjustProject" v-on="$listeners" :orgId="projectInfo.orgId"></adjust-project-dialog>
  </div>
</template>
<script>
import $ from 'jquery'
import AdjustProjectDialog from "@/views/material/dialogComponents/adjustProjectDialog.vue";

const MATERIAL_APPLICATION = [
    {
        label: '站址编码',
        prop: 'siteId',
        elProps: {
            width: '190px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '物料编码',
        prop: 'categoryCode',
        elProps: {
            width: '220px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '物料名称',
        prop: 'categoryName',
        elProps: {
            'show-overflow-tooltip': true
        }
    },
    {
        label: '物料精度',
        prop: 'spuUnitAcc',
        elProps: {
            'show-overflow-tooltip': true
        }
    },
    {
        label: '自定义规格',
        prop: 'dwjl',
        elProps: {
            width: '100px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '计量单位',
        prop: 'unit',
        elProps: {
            width: '100px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '主设备标识',
        prop: 'spuMainName',
        elProps: {
            width: '100px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '源头赋码标识',
        prop: 'ifSourceName',
        elProps: {
            width: '180px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '设计数量',
        prop: 'amount',
        details: '设计清单中该物料的数量',
        elProps: {
            width: '110px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '累计申领数量',
        prop: 'sumReceiveAmount',
        details: '该物料累计申领总数-累计撤销申领总数',
        elProps: {
            width: '110px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '实际出库数量',
        prop: 'osRealAmount',
        details: '该物料累计出库总数-累计已完成退库总数',
        elProps: {
            width: '110px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '可领取数量',
        prop: 'noReceiveAmount',
        details: '设计数量-累计申领数量',
        elProps: {
            width: '110px',
            'show-overflow-tooltip': true
        }
    },
    {
        label: '本次申领数量',
        prop: 'applyNum',
        elProps: {
            width: '130px',
            'show-overflow-tooltip': true
        }
    }
]
// 系统常量配置
import wzTable from './cTable'
import {
    doSaveApplyBySite,
    getShopTokenAndUrl,
    getSpuUnitAccByMaterialCode,
    doSaveAllApplyBySite,
    checkNodeByPrjId
} from '@/api/material'
import ResourceCodeAndLabel from "@/views/acceptanceManagement/materialServiceBind/components/resourceCodeAndLabel.vue";

export default {
    name: 'MaterialsApplication',
    components: {ResourceCodeAndLabel, wzTable,AdjustProjectDialog },
    props: {
        flag: {
            type: Number,
            default: 1
        },
        note: {
            type: String,
            default: ''
        },
        receiveDetailsData: {
            type: Object,
            default: () => ({})
        },
        outPut: {
            type: Boolean,
            default: true
        },
        metaEdit: {
            type: Boolean,
            default: true
        }
    },
    data() {
        return {
            fileList: [],
            designData: [],
            materialRemovalVisible: false,
            materialBackVisible: false,
            arrivalVisible: false,
            planGetTime: '',
            wzApplicationColumn: [],
            nonarrivalNumForm: {
                nonarrivalNum: ''
            },
            materialsRemarks: '',
            projectInfo: {
                projectName: '',
                orgName: '',
                prjCode: ''
            },
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() <= Date.now() - 24 * 60 * 60 * 1000
                }
            },
            loadingButton: false,
            observerWatcher: null,
            loading: false,
            isStandValueOptions: [
                { label: '是', value: '1' },
                { label: '否', value: '0' }
            ],
            showAdjustProject:false,
            checkAdjustButton:false,
            newProjectShow:false,//新流程需要先判断这个值
        }
    },
    computed: {
        query() {
            return this.$route.query
        },
        sjbgcheck() {
            if (this.receiveDetailsData.prjInfo) {
                return !!+this.receiveDetailsData.prjInfo.sjbgcheck
            }
            return false
        },
        reState() {
            if (this.receiveDetailsData.prjInfo) {
                return !+this.receiveDetailsData.prjInfo.reState
            }
            return false
        },
        acceptcheck() {
            if (this.receiveDetailsData.prjInfo) {
                return !+this.receiveDetailsData.prjInfo.acceptcheck
            }
            return true
        },
        isEdit() {
            if (this.receiveDetailsData.prjInfo) {
                return !!+this.receiveDetailsData.prjInfo.isEdit
            }
            return true
        },
        isStand() {
            // 否按备电标准化成品申领
            if (this.receiveDetailsData.prjInfo) {
                return !!+this.receiveDetailsData.prjInfo.isStand
            }
            return false
        },
        appendToBody() {
            this.receiveDetailsData
            return !(self !== top)
        },
        powerPermisson(){
            return +this.projectInfo?.isNewAcceptance===1&&+this.projectInfo?.acceptcheck===1&&this.newProjectShow
        },
    },
    watch: {
        receiveDetailsData: {
            handler(newValue) {
                this.projectInfo = newValue.prjInfo
                if (newValue.designData && newValue.designData.length) {
                    this.designData = newValue.designData
                    this.newProjectShow = this.designData.some(item=>+item.jwMateReceive===1)
                } else {
                    this.designData = []
                }
                this.projectInfo = { ...newValue.prjInfo }
                if (this.sjbgcheck) {
                    this.wzApplicationColumn.pop()
                } else {
                    this.wzApplicationColumn = JSON.parse(
                        JSON.stringify(MATERIAL_APPLICATION)
                    )
                }
                if (this.isStand) {
                    this.wzApplicationColumn = JSON.parse(
                        JSON.stringify(MATERIAL_APPLICATION)
                    )
                    this.wzApplicationColumn.splice(11, 0, {
                        label: '按备电标准化成品申领',
                        prop: 'isStandValue',
                        elProps: {
                            width: '160px',
                            'show-overflow-tooltip': true
                        }
                    })
                }
            },
            deep: true,
            immediate: true
        },
        materialsRemarks: {
            handler(newValue) {
                this.$emit('update:note', newValue)
            }
        }
    },
    beforeDestroy() {
        this.observerWatcher.disconnect()
    },
    created() {
        this.wzApplicationColumn = JSON.parse(
            JSON.stringify(MATERIAL_APPLICATION)
        )
        this.observerWatcher = new MutationObserver(() => {
            this.$nextTick(() => {
                if (!window.top.document.body) {
                    this.observerWatcher.disconnect()
                }
                const alertMessage = document.querySelector('.el-message')
                if (alertMessage) {
                    const contentBody = window.top.document.body
                    contentBody.appendChild(alertMessage)
                    this.observerWatcher.takeRecords()
                } else {
                    return
                }
            })
        })
        // 判断当前是否被iframe应勇
        if (self !== top) {
            this.observerWatcher.observe(document.body, {
                childList: true
            })
        }
    },
    mounted() {
        if (this.isStand) {
            this.wzApplicationColumn = JSON.parse(
                JSON.stringify(MATERIAL_APPLICATION)
            )
            this.wzApplicationColumn.splice(11, 0, {
                label: '按备电标准化成品申领',
                prop: 'isStandValue',
                elProps: {
                    width: '160px',
                    'show-overflow-tooltip': true
                }
            })
        }
        console.log(this.projectInfo)
        this.getCheckNodeByPrjId();
    },
    methods: {
        // 新权限
        newPowerShow(){
            return this.newProjectShow&&+this.projectInfo.reState===0&&+this.projectInfo.sjbgcheck===0
        },
        // 2025.4.1 通信智联新需求权限变更
        permissionChange(row){
            return +this.projectInfo.isEdit===0&&+this.projectInfo.reState===0&&this.nonarrivalDisabled(row)&&+this.projectInfo.sjbgcheck===0
        },
        getCheckNodeByPrjId(){
            checkNodeByPrjId(this.query.prjId).then((res)=>{
                if(+res.code === 200){
                    this.checkAdjustButton = true;
                }
            })
        },
        docTypeChange(value, row) {
            row.addStandValue = value
        },
        ifSourceCode(ifSourceCode) {
            if (+ifSourceCode) {
                return '否'
            }
            if (ifSourceCode === 0 || ifSourceCode === '0') {
                return '是'
            }
            return ifSourceCode
        },
        nonarrivalDisabled(row) {
            if (+row.noReceiveAmount > 0) {
                return false
            }
            return true
        },
        // 点击出库数量
        handleMaterialsDetail() {
            this.materialRemovalVisible = true
        },
        // 退库数量
        handleMaterialBackVisible() {
            this.materialBackVisible = true
        },
        // 已贴标签数量
        handleArrivalVisible() {
            this.arrivalVisible = true
        },
        async handleApplyrepaitrOne(){
            if (!this.planGetTime) {
                this.$message.warning('请选择计划领用时间')
                return Promise.reject()
            }
        },
        async handleApplyrepaitrTwo(res,loading){
            if (+res.code === 200) {
                loading ? loading.close() : (this.loading = false)
                this.$message.success('提交成功')
            }
        },
        async handleApplyrepaitrThree(loading){
            loading ? loading.close() : (this.loading = false)
        },
        async handleApplyrepaitrFour(getSpuUnitAccByMaterialCodeRes){
            if (+getSpuUnitAccByMaterialCodeRes.code !== 200) {
                return Promise.reject()
            }
        },
        async handleApplyrepaitrFive(){
            return this.projectInfo.siteName || ''
        },
        async handleApplyrepaitrSix(){
            return !(
                this.query.manageMode === '03' ||
                this.query.manageMode === '04'
            )
                ? 1
                : ''
        },
        async handleApplyrepaitrSeven(applyItem){
            let backdata = []
            if (applyItem.length) {
                for (const item of applyItem) {
                    item.isStandValue =
                        item?.addStandValue || item.isStandValue
                    console.log(item.standValue)
                    await this.handleApplyrepaitrEight(item)
                    backdata.push({
                        ...item,
                        receiveAmount: item.applyNum
                    })
                }
            } else {
                this.$message.warning('请输入对应站址的申领物资数量！')
                return Promise.reject()
            }
            return backdata
        },
        async handleApplyrepaitrEight(item){
            if (this.isStand) {
                if (!(item.isStandValue === '0' || item.isStandValue === '1')) {
                    this.$message.warning(
                        '请选择是否按备电标准化成品申领，并正确输入申领数量，申领数量不能大于可领取数量！申领数量精度需正确!'
                    )
                    return Promise.reject()
                }
            }
        },
        adjustProject(){
            this.showAdjustProject=true;
        },
        // 单个项目确认领用
        async handleApply() {
            await this.handleApplyrepaitrOne()
            const applyItem = this.designData.filter(
                (item) => +item.applyNum > 0
            )
            const prjInfo = {
                adjId: '',
                applyType: '1',
                note: this.materialsRemarks,
                pagesize: 10,
                planTime: this.planGetTime,
                prjId: this.query.prjId
            }
            let applys = []
            applys = await this.handleApplyrepaitrSeven(applyItem)
            const params = {
                applys,
                prjInfo
            }
            for (const row of applys) {
                const materialCheckParams = {
                    receiveAmount: row.receiveAmount,
                    materialCode: row.categoryCode,
                    amountType: 1, // 撤销领用
                    siteName:await this.handleApplyrepaitrFive(),
                    queryType:await this.handleApplyrepaitrSix(),
                    note: this.note,
                    siteId: row.siteId
                }
                const getSpuUnitAccByMaterialCodeRes =
                    await getSpuUnitAccByMaterialCode(materialCheckParams)
                await this.handleApplyrepaitrFour(getSpuUnitAccByMaterialCodeRes)
            }

            this.loadingButton = true
            const timer = setTimeout(() => {
                this.loadingButton = false
                clearTimeout(timer)
            }, 5 * 1000)
            let loading = null
            if (self !== top) {
                this.loading = true
            } else {
                loading = this.$loading({
                    lock: true,
                    text: '物资申领中,请稍后...',
                    spinner: 'el-icon-loading',
                    fullscreen: false
                })
            }

            try {
                const res = await doSaveApplyBySite(params)
                await this.handleApplyrepaitrTwo(res,loading)
            } catch (error) {
                await this.handleApplyrepaitrThree(loading)
            } finally {
                this.$emit('doSaveApplyBySite')
                await this.handleApplyrepaitrThree(loading)
            }
        },
      // 一键领用
      async handleAllApply() {
        if (!this.planGetTime) {
          return this.$message.warning('请选择计划领用时间')
        }
        const params = {
          note: this.materialsRemarks,
          planTime: this.planGetTime,
          prjId: this.query.prjId
        }
        this.loadingButton = true
        const timer = setTimeout(() => {
          this.loadingButton = false
          clearTimeout(timer)
        }, 5 * 1000)
        let loading = null
        if (self !== top) {
          this.loading = true
        } else {
          loading = this.$loading({
            lock: true,
            text: '物资申领中,请稍后...',
            spinner: 'el-icon-loading',
            fullscreen: false
          })
        }

        try {
          const res = await doSaveAllApplyBySite(params)
          if (+res.code === 200) {
            loading ? loading.close() : (this.loading = false)
            this.$message.success('提交成功')
          }
        } catch (error) {
          loading ? loading.close() : (this.loading = false)
        } finally {
          this.$emit('doSaveApplyBySite')
          loading ? loading.close() : (this.loading = false)
        }
      },
        // 未贴标签数量
        // 已到货确认数量
        // 未到货确认数量
        // 点击
        async jump(prjCode) {
            const res = await getShopTokenAndUrl({
                prjCode
            })
            if (+res.code === 200) {
                const data = res.data
                const toUrl = `${data.assetsResource.url}systemManagement/pmsOutstockQuery`
                const params = {}
                // acctId=${data.assetsResource.acctId}&token=${data.assetsResource.token}&username=${data.assetsResource.userId}&cityName=${data.cityName}&projectCode=${data.prjCode}&projectName=${data.projectName}&provinceCode=${data.provinceCode}&orgCode=${data.orgCode}
                params.token = data.assetsResource.token
                params.acctId = data.assetsResource.acctId
                params.username = data.assetsResource.userId
                params.cityName = data.cityName ?? 'null'
                params.projectCode = data.prjCode
                params.projectName = data.projectName
                params.provinceCode = data.provinceCode
                params.orgCode = data.orgCode
                const newWin = window.open()
                const form = $("<form method='get'></form>")
                form.attr({ action: toUrl })
                $.each(params, function(key, value) {
                    const input = $("<input type='hidden' />")
                    input.attr({ name: key })
                    input.val(value)
                    form.append(input)
                })
                form.appendTo(newWin.document.body)
                form.submit()
            }
        }
    }
}
</script>
<style scoped lang="scss">
.el-upload--text {
    width: 100%;
}
.btnflex {
    display: flex;
    justify-content: space-between;
}
.el-table th {
    padding: 0px 0;
    text-align: center;
    font-size: 12px;
    color: #333333;
    letter-spacing: 0;
}
.el-table td {
    padding: 0px 0;
    text-align: center;
    font-size: 2px;
    color: #333333;
    letter-spacing: 0;
}
.click-row {
    color: #53c7f8;
    cursor: pointer;
}
.materials-remark-wrapper {
    position: relative;
    border: 1px solid #ccc;
    padding-left: 10px;
    padding-right: 10px;
    padding-top: 20px;
    padding-bottom: 10px;
    &-title {
        position: absolute;
        left: 50%;
        top: -13px;
        background: #fff;
        font-weight: bold;
    }
}

.mt-10 {
    margin-top: 10px;
}
.mb-10 {
    margin-bottom: 10px;
}
.mb-5 {
    margin-bottom: 5px;
}
.flex-box {
    display: flex;
    width: 100%;
    align-items: center;
    height: auto;
    position: relative;
    &-left {
        margin-right: auto;
    }
}
.pms-el-datepicker {
    margin-left: 10px;
    margin-right: 10px;
    height: 24px;
    ::v-deep .el-input__inner {
        height: 24px;
    }
    ::v-deep .el-input__icon {
        line-height: 20px;
    }
}
.position-abs {
    position: absolute;
}
.abs-right {
    right: 10px;
}
::v-deep .el-loading-spinner {
    margin-top: -11px;
    .circular {
        width: 20px;
        height: 20px;
    }
}
.pms-wz-input {
    ::v-deep .el-input__inner {
        background-color: #fffaee !important;
    }
    ::v-deep .el-input__inner:disabled {
        background-color: #f5f7fa !important;
    }
}
</style>
